package org.xxx.epms.inspector.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.xxx.epms.common.exception.Asserts;
import org.xxx.epms.common.utils.JwtTokenUtil;
import org.xxx.epms.inspector.dto.InspectorParam;
import org.xxx.epms.inspector.mapper.InspectorMapper;
import org.xxx.epms.inspector.model.Inspector;
import org.xxx.epms.inspector.model.InspectorDetails;
import org.xxx.epms.inspector.service.InspectorService;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lb
 * @since 2024-06-08
 */
@Service
public class InspectorServiceImpl extends ServiceImpl<InspectorMapper, Inspector> implements InspectorService {

    private static final Logger LOGGER = LoggerFactory.getLogger(InspectorServiceImpl.class);

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private InspectorMapper inspectorMapper;

    private QueryWrapper<Inspector> getQueryWrapper(InspectorParam inspectorParam){
        QueryWrapper<Inspector> wrapper = new QueryWrapper<>();
        if(inspectorParam.getInsId() != null){
            wrapper.lambda().eq(Inspector::getInsId, inspectorParam.getInsId());
        }
        if(inspectorParam.getInsName() != null){
            wrapper.lambda().like(Inspector::getInsName, inspectorParam.getInsName());
        }
        if(inspectorParam.getInsTel() != null){
            wrapper.lambda().eq(Inspector::getInsTel, inspectorParam.getInsTel());
        }
        if(inspectorParam.getProvinceId() != null){
            wrapper.lambda().eq(Inspector::getProvinceId, inspectorParam.getProvinceId());
        }
        if(inspectorParam.getCityId() != null){
            wrapper.lambda().eq(Inspector::getCityId, inspectorParam.getCityId());
        }
        if(inspectorParam.getInsAddress() != null){
            wrapper.lambda().like(Inspector::getInsAddress, inspectorParam.getInsAddress());
        }
        if(inspectorParam.getRemarks() != null){
            wrapper.lambda().like(Inspector::getRemarks, inspectorParam.getRemarks());
        }
        if(inspectorParam.getInsState() != null){
            wrapper.lambda().eq(Inspector::getInsState, inspectorParam.getInsState());
        }
        return wrapper;
    }


    @Override
    public Page<Inspector> getInspectorList(InspectorParam inspectorParam, int pageNum, int pageSize) {
        if(inspectorParam == null){
            Page<Inspector> page = new Page<>(pageNum, pageSize);
            return page(page, null);
        }else{
            QueryWrapper<Inspector> wrapper = getQueryWrapper(inspectorParam);
            Page<Inspector> page = new Page<>(pageNum, pageSize);
            return page(page, wrapper);
        }
    }

    @Override
    public int getInspectorListTotalPage(InspectorParam inspectorParam, int pageSize) {
        if(inspectorParam.getInsId() == null){
            //计算总页数
            long total = inspectorMapper.selectCount(null);
            return (int)total / pageSize + (total % pageSize > 0? 1 : 0);
        }else {
            QueryWrapper<Inspector> wrapper = getQueryWrapper(inspectorParam);
            long total = inspectorMapper.selectCount(wrapper);
            return (int) total / pageSize + (total % pageSize > 0 ? 1 : 0);
        }
    }

    @Override
    public Inspector getInspectorByInsId(Integer insId) {
        QueryWrapper<Inspector> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Inspector::getInsId, insId);
        Inspector inspector = inspectorMapper.selectOne(wrapper);
        return inspector;
    }

    @Override
    public Inspector getInspectorByInsTel(String insTel) {
        QueryWrapper<Inspector> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Inspector::getInsTel, insTel);
        Inspector inspector = inspectorMapper.selectOne(wrapper);
        return inspector;
    }

    @Override
    public String login(InspectorParam inspectorParam) {
        String token = null;
        //密码需要客户端加密后传递
        if(getInspectorByInsId(inspectorParam.getInsId()) == null){
            Asserts.fail("网格员编码不存在");
        }
        UserDetails inspectorDetails = loadUserByUsername(inspectorParam.getInsId());
        try {
            if(!passwordEncoder.matches(inspectorParam.getInsPassword(),inspectorDetails.getPassword())){
                Asserts.fail("密码错误");
            }
            if(!inspectorDetails.isEnabled()){
                Asserts.fail("帐号已被禁用");
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(inspectorDetails, null);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(inspectorDetails);
        } catch (AuthenticationException e) {
            LOGGER.warn("登录异常:{}", e.getMessage());
        }
        return token;
    }

    @Override
    public InspectorDetails loadUserByUsername(Integer username){
        //获取管理员信息
        Inspector inspector = getInspectorByInsId(username);
        if (inspector != null) {
            return new InspectorDetails(inspector);
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    }

    @Override
    public Inspector register(InspectorParam inspectorParam) {
        Inspector inspector = new Inspector();
        BeanUtils.copyProperties(inspectorParam, inspector);

        //检验参数合法性 -> 网格员编码是否已被注册
        if(inspectorMapper.selectOne(new QueryWrapper<Inspector>().eq("ins_id", inspector.getInsId()))!= null){
            Asserts.fail("网格编码已被注册!");
        }else{
            inspector.setInsPassword(passwordEncoder.encode(inspector.getInsPassword()));
            if(inspectorMapper.insert(inspector) > 0) {
                return inspector;
            }else {
                Asserts.fail("注册失败!");
            }
        }
        return null;
    }
}
